package day03;

import lombok.extern.slf4j.Slf4j;
import utils.Sleeper;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁超时
 */
@Slf4j
public class test3 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("尝试获取锁");
                try {
                    if (!lock.tryLock(2, TimeUnit.SECONDS)) {
                        log.debug("获取不到锁");
                        return;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                try {
                    log.debug("获取到锁");
                } finally {
                    lock.unlock();
                }

            }
        };

        // 主线程获取到锁
        lock.lock();
        t1.start();
        Sleeper.sleep(1);
        lock.unlock();
    }

}
